// pages/member/index_v2/index_v2.js
var app = getApp();
const innerAudioContext = wx.createInnerAudioContext();
var getInvite = require("../../mybehaviors/getInvite/getInvite");
const skinBehavior = require('../../utils/themeSkin/skinBehavior');
var location = require("../../mybehaviors/location/location");

Page({
  behaviors: [getInvite, skinBehavior,location],
  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: null,
    loading: true,
    is_login: 0,

    U_tabcontrol: true,
    order_active: 0,
    plugin_active: 'recommendGoods',
    service: "",
    showPopup: false,
    decorate_isLoadMore: true,

    // 默认组件数据
    btnData: {
      "button_size": 40,
      "over_top": 500,
      "position_location": "right",
      "icon_url": ""
    },
    recommendGoods: {
      "preview_color": "#f5f5f5",
      "sort_style": {
        "choose_icon": "2"
      },
      "padding_top": 0,
      "padding_bottom": 0,
      "padding_left": 10,
      "padding_right": 10,
      "item_radius": 5,
      "show_shadow": false,
      "show_border": false,
      "border_color": "#BFB7B7",
      "good_tag": {
        "choose_icon": "0",
        "image": ""
      },
      "button_type": "3",
      "button_title": "立即购买",
      "button_bg_color": "#ff2c29",
      "button_color": "#ffffff",
      "content_list": [
        "1",
        "3",
        "4",
        "7"
      ],
      "show_price_text": false,
      "disable_good": "0",
      "goods_type": "list",
      "list": []
    },
    limitBuyGoods: {
      "preview_color": "#f5f5f5",
      "sort_style": {
        "choose_icon": "2"
      },
      "padding_top": 0,
      "padding_bottom": 0,
      "padding_left": 10,
      "padding_right": 10,
      "item_radius": 5,
      "show_shadow": false,
      "show_border": false,
      "border_color": "#BFB7B7",
      "good_tag": {
        "choose_icon": "0",
        "image": ""
      },
      "button_type": "3",
      "button_title": "立即购买",
      "button_bg_color": "#ff2c29",
      "button_color": "#ffffff",
      "content_list": [
        "1",
        "3",
        "4",
        "7"
      ],
      "show_price_text": false,
      "disable_good": "0",
      "goods_type": "list",
      // "list": []
    },
    article: {
      "get_style": "1",
      "get_number": 999,
      "article_style": "2",
      "article_bg": "#f5f5f5",
      "show_tab": true,
      "article_tab_bg": "#ffffff",
      "title_color": "#333",
      "title_active_color": "#ff2c29"
    },
    storeCashier: {
      "get_number": 999,
      "preview_color": "#f5f5f5",
      "font_size": 14,
      "font_color": "#666666",
      "border_radius": 35,
      "class_font_size": 14,
      "class_font_color": "#ffffff",
      "class_bg_color": "#adadad",
      "class_border_radius": 5,
      "location_font_size": 14,
      "location_font_color": "#666666",
      "discount_font_size": 14,
      "discount_title_color": "#ff2c29",
      "discount_font_color": "#666666",
      "discount_list": [
        "1",
        "2",
        "3",
        "4"
      ],
      "tag_font_size": 14,
      "tag_font_color": "#666666",
      "tag_bg_color": "#f3f2f2",
      "tag_border_color": "#ff8400",
      "tag_border_radius": 5,
      "show_goods": true,
      "tab_list": [],
      "tab_bg_color": "#ffffff",
      "tab_color": "#333333",
      "tab_active_color": "#ff8400"
    },
    microCommunities: {
      "get_style": "1",
      "get_number": 999,
      "preview_color": "#f5f5f5",
      "tab_bg": "#ffffff",
      "title_color": "#333",
      "title_active_color": "#ff2c29",
    },
    videoShare: {
      "preview_color": "#f5f5f5",
      "get_style": "1",
      "get_number": 999
    },
    room: {
      choose_tab: "0",
      get_number: 20,
      preview_color: "#f5f5f5",
      record_id: 1,
      tab_active_color: "#ff2c29",
      tab_bg_color: "#ffffff",
      tab_color: "#333333",
    },
    fightGroups: {},
    ywmFightGroups: {},

    templateValue: '02', //模板样式 (目前有三种，模板1、模板2、装修diy页面)
    member_info: {
      avatar:`${app.globalData.imgPath}images%2Fphoto-mr.jpg`,
    }, //顶部会员信息
    order: [], //订单列表信息
    plugin_data: [], //底部选项卡
    plugins: [], //插件入口汇总
    assets: [], //资产数据
    foot: {}, //底部版权模块

    // 登录弹窗
    lsgow: false,
    language: {},

    isshow: false, //判断二维码的显示
    footshow: false,
    firstshow: false,

    showcarrfootBol: false,
    iPnoneBottomBol: false,

    //新装修
    page_id: "",
    components: [],
    advertising: {},
    clientWidth: "375",
    popShow: false,
    btnFlag: false,
    bottomShowBol: false,
    bottomShowBolIndex: 0,

    showChangeID: false,
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    AuthorizedPhone: '',

    // 平台协议
    PlatformAgreement: '',
    openPlatformAgreement: false,
    tapSelectAgreement: false,
    agreement_name: '平台协议',

    store_alone_temp: 0, // 企业独立参数
    // 兼容登录
    canIUseGetUserProfile: false,
    showAutoBindPhone: false, // 首次授权登录自动绑定手机号(PS：新会员！！！首次)

    // 团队名称显示
    teamNameShow: false,
    // 显示设置昵称头像弹窗,
    editMemberPopupShow: false,
    imgPath: app.globalData.imgPath,
    is_mini_logout_button:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getUserProfile) {
      // 兼容pc小程序登录
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    this.getiPnoneBottom(); // 获取是否需要iponex底部安全区

    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
    wx.removeStorageSync("setNewDecorateMember");
    this.basic_info = wx.getStorageSync('yz_basic_info') || {};
    this.setData({
      mailInfo: this.basic_info.home ? this.basic_info.home.mailInfo : {},
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    if (language) {
      this.setData({
        language: language.en,
      });
      wx.setNavigationBarTitle({
        title: this.data.language["会员中心"],
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    // setNewDecorateMember是否已经请求会员数据
    var value = wx.getStorageSync("setNewDecorateMember");
    if (value != 1) {
      this.getMemberData();
      wx.setStorageSync("setNewDecorateMember", "1");
    }
  },
  toUrl(e) {
    let _data = e.currentTarget.dataset || {};
    this.wxRouterLink(_data);
  },
  wxRouterLink(_data) {
    let _Param = "";
    const {
      url,
      ...otherParam
    } = _data;
    Object.keys(otherParam).forEach(function (key) {
      if (otherParam[key] !== "") _Param += key + "=" + otherParam[key] + "&";
    });
    if (url === "") return;
    wx.navigateTo({
      url: url + "?" + _Param.slice(0, -1),
    });
  },
  //爱心音频功能
  assetsAudio(otherData,audioFlag) {
    if(audioFlag) {
      innerAudioContext.src = otherData?.mark_sound?.sound_link //设置音频地址
      innerAudioContext.loop = false // 是否循环播放
      innerAudioContext.play(); //播放音频
    }
  },
  //处理爱心值装修数据
  setAssetData(datas,other) {
    if(datas && datas.length > 0){
      let memberasset = datas.filter((item) => item.component_key == 'U_memberasset');
      let showList = memberasset[0]?.remote_data?.show_list;
      let audioFlag = false;
      if(showList && showList.length > 0) {
        audioFlag = showList.some((item) => item.is_change == 1);
      }
      this.assetsAudio(other,audioFlag);
    }
  },
  getMemberData() {
    if (app.globalData.store_alone_temp == 1) {
    return this.getStoreMember(); // 开启企业独立模块
    }

    let urlStr = app.getNetAddresss("member.member.member-data");
    app._getNetWork({
      url: urlStr,
      data: {
        v: 2,
        basic_info: 1
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result === 1) {
          wx.stopPullDownRefresh();
          let {
            member_info,
            order,
            plugin_data,
            plugins,
            assets,
            foot,
            designer,
            other,
            is_login
          } = res.data;
          let _data = {};
          _data.templateValue = '01';
          _data.footshow = true;
          _data.is_login = is_login !== undefined ? is_login: 1;

          let basic_info = res.basic_info; // 从yz_basic_info获取新装修设置
          if(basic_info?.plugin_setting?.integral?.needSign && _data.is_login) {
            wx.showModal({
              title: '提示',
              content: '请先完成合同签署',
              success (res) {
                if (res.confirm) {
                  return wx.navigateTo({
                    url: '/packageH/sign_shopV2/index/index?scene=4',
                  });
                }
              }
            })
          }
          if (other?.setting?.member_auth_pop_switch == 1 && _data.is_login) {
            if (other.setting.has_avatar == 0) {
              // 没有头像 或者 没有设置昵称 显示设置昵称头像弹窗 #7592
              this.setData({
                editMemberPopupShow: true
              })
            }
          }
          this.setData({
            is_mini_logout_button:other?.is_mini_logout_button == 1 ? true : false
          })

          if(!_data.is_login) {
            let showinfo = basic_info;
            if (showinfo.home && showinfo.home.register_setting) {
              let {
                new_agreement,
                agreement_name,
                default_tick
              } = showinfo.home.register_setting;
              try {
                this.setData({
                  PlatformAgreement: new_agreement ? new_agreement.replace(/<img/g, '<img style="width:100%;display:flex;"') : '',
                  agreement_name: app._isTextEmpty(agreement_name) ? this.data.agreement_name : agreement_name,
                  tapSelectAgreement :default_tick == 1?true:false
                });
              } catch (error) {
                console.log(error);
              }

              let shopName = showinfo.home.mailInfo.name;
              if (app._isTextEmpty(showinfo.home.register_setting.title1)) {
                showinfo.home.register_setting.title1 = `欢迎来到${shopName}`;
              }
              if (app._isTextEmpty(showinfo.home.register_setting.title2)) {
                showinfo.home.register_setting.title2 = "登录尽享各种优惠权益！";
              }
              this.setData({
                showinfo: showinfo.home.register_setting,
                //lsgow: true
              });
            } else {
              this.setData({
                showinfo: {
                  title1: "欢迎来到",
                  title2: "登录尽享各种优惠权益！"
                }
              });
            }
          }

          if (designer) {
            _data.components = designer.datas;
            _data.templateValue = "designer";
            _data.firstshow = true;
            _data.foot = foot;
            _data.other = other;
            _data.loading = false;
            this.getNewDecorate(designer);
            this.setData(_data);
            this.setAssetData(designer.datas,other);
            return; //设置装修后，这里 return 了，不走下面逻辑 ！！！！！！！！！！！！！
          } else if (basic_info && basic_info.home.item.is_decorate === 1) {
            if (basic_info.home.item.ViewSet.member.is_default != 0) {
              _data.templateValue = basic_info.home.item.ViewSet.member.code.substring(6); //获取模板设置
            } else {
              _data.templateValue = "01";
            }
          }
          
          _data.member_info = member_info;
          _data.order = order;
          _data.plugin_data = plugin_data;
          _data.plugins = plugins;
          _data.assets = assets;
          _data.foot = foot;
          _data.other = other;
          let audioFlag = assets.some((item) => item.is_change == 1);
          this.assetsAudio(other,audioFlag);
          if (plugins.body) {
            // 换成图片改成后端返回 #33991
            // plugins.body.push({
            //   class: "icon-zb_all_more",
            //   image: "",
            //   mini_url: "/packageG/morePlugin/morePlugin",
            //   name: "morePlugin",
            //   title: "更多工具",
            //   url: "morePlugin"
            // });
            let page = Math.ceil(plugins.body.length / 10); //==> 页数
            let num = 10; // ==> 每页多少个
            let _plugin_list = [];
            for (let i = 0; i < page; i++) {
              _plugin_list.push(plugins.body.slice(i * num, (i + 1) * num));
            }
            _data.plugins.body = _plugin_list;
          }

          if (plugin_data && plugin_data.length > 0) {
            if (plugin_data.length > 0) {
              // 模板1 底部选项卡装修，后端默认返回第一个标签页对应的列表数据
              _data.plugin_active = plugin_data[0].code; 
              const activePlugin = this.data[_data.plugin_active]; 
              const pluginData = plugin_data[0]?.data; 
              
              activePlugin.current_page = pluginData?.current_page; 
              activePlugin.last_page = pluginData?.last_page; 
              
              switch (_data.plugin_active) { 
                case 'microCommunities': 
                case 'storeCashier': 
                case 'limitBuyGoods': 
                  activePlugin.list = pluginData || []; 
                  break; 
                case 'videoShare': 
                  activePlugin.list = pluginData?.list || []; 
                  activePlugin.current_page = pluginData?.list?.current_page; 
                  activePlugin.last_page = pluginData?.list?.last_page; 
                  break; 
                case 'article': 
                  activePlugin.list = pluginData?.articles || []; 
                  activePlugin.current_page = pluginData?.articles?.current_page; 
                  activePlugin.last_page = pluginData?.articles?.last_page; 
                  break; 
                default: 
                  activePlugin.list = pluginData?.data || []; 
                  break; 
              } 
              _data[_data.plugin_active] = this.data[_data.plugin_active];
            }
          }

          if (_data.templateValue !== 'designer') {
            wx.setNavigationBarColor({
              frontColor: '#ffffff',
              backgroundColor: this.data.themeBaseColor,
              animation: {
                duration: 400,
                timingFunc: 'easeIn'
              }
            });
          }

          if (other.service) {
            if (typeof (other.service) !== 'string') {
              this.setData({
                service: other.service
              });

              if (other.service.customer_open == "0") {
                this.setData({
                  service: false
                });
              }
            }
          }

          if (!app._isTextEmpty(res.data.foot)) {
            this.setData({
              cat_adv_url: res.data.foot.small_cat_adv_url
            })
          }
          this.setData(_data);
          
          wx.setStorage({
            key: "uid",
            data: member_info.member_id,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
        this.setData({
          firstshow: true,
          loading: false
        });
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      isshow: false,
    });
    if(innerAudioContext) {
      innerAudioContext.stop();
    }
  },

  // 平台协议勾选  
  PlatformAgreementOnChange(e) {
    this.setData({
      tapSelectAgreement: e.detail
    });
  },
  PlatformAgreementTap() {
    this.setData({
      openPlatformAgreement: true
    });
  },
  PlatformAgreementClose() {
    this.setData({
      openPlatformAgreement: false
    });
  },
  // 平台协议  end

  copyLink() {
    if (!app._isTextEmpty(this.data.foot.small_cat_adv_url)) {
      wx.navigateTo({
        url: this.data.foot.small_cat_adv_url,
      })
    }
  },
  //获取模板id
  getTemplate_1(small_type, url) {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: small_type,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          wx.requestSubscribeMessage({
            tmplIds: array,
            success(res) {
              wx.navigateTo({
                url: url
              });
            },
            fail() {
              wx.navigateTo({
                url: url
              });
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  getiPnoneBottom() {
    try {
      var value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        this.setData({
          iPnoneBottomBol: true,
        });
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // #87379 清除首页装修缓存
    wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
    this.setData({
      order:[]
    })
    if(innerAudioContext) {
      innerAudioContext.stop();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 下拉刷新
    console.log('onPullDownRefresh', new Date());
    this.getMemberData();
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // 节流
    if (e.scrollTop > 80 && !this.data.btnFlag) {
      this.setData({
        btnFlag: true,
      });
    } else if (e.scrollTop <= 80 && this.data.btnFlag) {
      this.setData({
        btnFlag: false,
      });
    }

    if (this.data.bottomShowBol) {
      this.setData({
        bottomShowBol: false,
      });
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      bottomShowBol: true,
    });

    if (this.data.decorate_isLoadMore) {
      if (this.data.templateValue === "designer") {
        this.getMoreDecorate();
      } else if (this.data.templateValue === "01") {
        this._handleBottomPluginData(this.data.plugin_active, "getMore");
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {},
  onShareAppMessage: function () {
    return {
      path: "/packageG/index/index",
    };
  },
  loginOutPost(){
    let urlStr = app.getNetAddresss("member.logout.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          // 清除相关本地缓存
          wx.removeStorageSync('session');
          wx.removeStorageSync('nickname');
          wx.removeStorageSync('wx_token');
          wx.removeStorageSync('new_decorate');
          wx.removeStorageSync('openid');
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('yz_uid');
          wx.navigateTo({
            url: '/pages/login/login?isOut=1',
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  closePop() {
    this.setData({
      popShow: false,
    });
  },
  toEditAvatar(){
    wx.navigateTo({
      url: '/packageA/member/new_userinfo/new_userinfo',
    })
  },
  editMemberPopupClose(e) {
    // 编辑用户昵称和头像
    if(this.data.templateValue === 'designer'){
      const index = this.data.components.findIndex(obj => obj.component_key === "U_membertop");//查找【会员中心】装修组件对应的索引值
      if(index > -1 ) {
        let _member_info = this.data.components[index].remote_data.data;
        if(e.detail.name) _member_info.nickname = e.detail.name;
        if(e.detail.avatar) _member_info.avatar = e.detail.avatar;
        this.setData({
          ['components['+ index +'].remote_data.data']: _member_info
        })
        return;
      }
    }
    
    
    if (e.detail.avatar) {
      this.setData({
        ['member_info.avatar']: e.detail.avatar
      })
    }
    if (e.detail.name) {
      this.setData({
        ['member_info.nickname']: e.detail.name
      })
    }
    if(this.data.member_info.member_team && e.detail.avatar){
      this.setData({
        ['member_info.member_team.avatar']: e.detail.avatar
      })
    }
  },

  clickOrderTab(e) {
    // if (this.data.order_list[e.detail.name].name == "ys_system") {
    //   // 益生线下订单
    //   wx.navigateTo({
    //     url: "/packageA/member/myOrder_v2/myOrder_v2?status=0&orderType=ysSystem",
    //   });
    // }
  },

  //跳转至会员权益
  gotoMemberGrade() {
    if (this.data.member_info.jump_level_page) {
      wx.navigateTo({
        url: "/packageB/member/MemberGradeList/MemberGradeList",
      });
    }
  },

  //根据后台返回名字做跳转
  pluginGoto(e) {
    let item = e.currentTarget.dataset.item;
    // 要测试这里  特殊情况有 courier、extension、collageIndex、cloudIndex、HotelManage酒店管理 ！！！！！！！！！！
    if (item.url == "SupplierCenter") {
      let uid = wx.getStorageSync('yz_uid')||0;
      const _url_1 = "/packageA/member/SupplierCenter/SupplierCenter?uid=" + uid
      this.getTemplate_1(4, _url_1);
    } else if (item.url == "storeManage") {
      //跳转到企业管理
      this.getTemplate_1(5, "/packageC/o2o/storeManage/storeManage");
    } else if (item.url == "helperLiveList") {
      this.getTemplate_1(6, "/packageD/directSeeding/helperLiveList/helperLiveList");
    } else if (item.name == "m-erweima" && item.mini_url == 'm-erweima') {
      // 海报
      this.openQrCode(this.data.dataIs);
    }else if(item.name == 'water_machine_consumer'){
      let device_no = wx.getStorageSync('device_no');
      let mini_url = item.mini_url;
      if(device_no){
        mini_url =  mini_url + '?device_no='+device_no;
      }
      wx.navigateTo({
        url: mini_url
      });
    }else if (item.mini_url) {
      let mini_url = item.mini_url;
      if(item.page_data && item.page_data.data_url) {
        mini_url = mini_url + `?api=${item.page_data.data_url}`;
      }
      if(item.page_data && item.page_data.date_time) {
        mini_url = mini_url + `&date_time=1`;
      }
      if(item.page_data && item.page_data.extparams) {
        mini_url = mini_url + `&extparams=${ JSON.stringify(item.page_data.extparams)}` 
      }
      if(item.page_data && item.page_data.plu) {
        mini_url = mini_url + `${item.page_data.data_url ? '&' : '?'}plu=${item.page_data.plu}`;
      }
      if(item.page_data && item.page_data.id) {
        mini_url = mini_url + `?id=${item.page_data.id}`;
      }
      wx.navigateTo({
        url: mini_url
      });
    }
  },

  openQrCodebtn() {
    this.openQrCode(this.data.dataIs);
  },
  showcarrfoot(e) {
    this.setData({
      showcarrfootBol: e.detail,
    });
  },

  openQrCode(e) {
    this.setData({
      isshow: true,
    });
  },
  // 隐藏二维码
  clicktapshow() {
    this.setData({
      isshow: false,
      lsgow: false,
    });
  },

  copybtn() {
    let inviteCode = this.data.member_info.invite_code;
    wx.setClipboardData({
      data: inviteCode ? inviteCode : "",
      success(res) {
        wx.showToast({
          icon: "none",
          title: "复制成功",
          duration: 1500,
        });
      },
    });
  },

  getNewDecorate(data) {
    this.setData({
      page_id: data.id,
      components: data.datas,
      decorate_isLoadMore: true,
    });
    if (data.page) {
      this.setData({
        total_page: data.page.total_page,
        current_page: data.page.current_page,
        bottomShowBolIndex: data.page.count - 1,
      });
    }

    if (data.page_info) {
      this.setData({
        advertising: data.page_info.advertising_id,
      });

      if (this.data.advertising.id && this.data.advertising.datas) {
        this.data.advertising.datas = JSON.parse(this.data.advertising.datas);
        this.setData({
          advertising: this.data.advertising,
        });
      }
    }

    let firstAdvertisement = wx.getStorageSync("firstAdvertisement");
    // 每个浏览周期只弹出一次
    if (
      this.data.advertising &&
      this.data.advertising.id &&
      !firstAdvertisement &&
      this.data.advertising.show_rule === 1
    ) {
      wx.setStorageSync("firstAdvertisement", true);
      this.setData({
        popShow: true,
      });
    }

    let popAdvertisement_expiration = wx.getStorageSync("member_popAdvertisement_expiration");
    let pop_newTime = parseInt(Date.parse(new Date()) / 1000);
    if (
      this.data.advertising &&
      this.data.advertising.id &&
      this.data.advertising.show_rule === 2 &&
      popAdvertisement_expiration < pop_newTime
    ) {
      let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
      wx.setStorageSync("member_popAdvertisement_expiration", timestamp);
      //每日小程序登录弹出
      this.setData({
        popShow: true,
      });
    }
  },
  getMoreDecorate() {
    this.setData({
      decorate_isLoadMore: false,
    });

    if (this.data.current_page < this.data.total_page) {
      this.data.current_page = this.data.current_page + 1
      let urlStr = app.getNetAddresss("plugin.decorate.frotend.decorate-api.get-page");
      app._postNetWork({
        url: urlStr,
        data: {
          decorate_page: this.data.current_page,
          decorate_id: this.data.page_id,
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.data.decorate_isLoadMore = true;
            this.data.components = this.data.components.concat(res.data.datas);
          } else {
            this.data.decorate_isLoadMore = false;
            this.data.components = this.data.current_page - 1;
          }
        },
      });
    }
  },
  getStoreMember() {
    // 企业独立模板
    let urlStr = app.getNetAddresss(
      "plugin.store-alone-temp.frontend.member.index"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        v: 2
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let memberInfo = res.data;
          let _data = {
            store_alone_temp: 1,
            assets: [],
            plugin_data: [],
            member_info:{
              invite_code: memberInfo.member.inviteCode.code ? memberInfo.member.inviteCode.code : "",
              is_agent: 1,
              invite_code_status: memberInfo.member.inviteCode.status ? memberInfo.member.inviteCode.status : "",
              avatar: memberInfo.member.avatar,
              nickname: memberInfo.member.nickname,
              member_id: memberInfo.member.uid,
              level_name: memberInfo.member.level_name,
            },
            foot: {
              copyright_img: memberInfo.member.copyrightImg,
              copyright: memberInfo.member.copyright
            },
            plugins: {
              body: [],
              head: []
            },
            templateValue: '01',
            footshow: true,
            loading: false,
            is_login: 1
          }
          console.log(res.data,'首次授权登录自动绑定手机号')
          if (res.data.is_first_time_bind) {
            // 首次授权登录自动绑定手机号 #22736
            this.setData({
              showAutoBindPhone: true
            });
          }
          if (res.data.member.has_avatar == 0) {
            // 独立企业 没有头像 或者 没有设置昵称 显示设置昵称头像弹窗 #20413
            this.setData({
              editMemberPopupShow: true
            })
          }
          if(memberInfo.member.coupon?.is_show){
            _data.assets.push({
              min_url: "/packageA/member/coupon_v2/coupon_v2",
              name: memberInfo.member.coupon.text,
              unit: "",
              url: "coupon",
              value: memberInfo.member.coupon.data
            })
          }
          if(memberInfo.member.integral?.is_show){
            _data.assets.push({
              min_url: "/packageB/member/Integral_love/Integral_love",
              name: memberInfo.member.integral.text,
              unit: "",
              url: "integral",
              value: memberInfo.member.integral.data
            })
          }
          if(memberInfo.member.credit?.is_show){
            _data.assets.push({
              min_url: "/packageI/independenceBalance/independenceBalance?store_id=" + app.globalData.STORE_ID,
              name: memberInfo.member.credit.text,
              unit: "",
              url: "balance",
              value: memberInfo.member.credit.data
            })
          }
          if(memberInfo.member.integral_show?.is_show){
            _data.assets.push({
              min_url: "/packageB/member/Integral_love/Integral_love",
              name: memberInfo.member.integral_show.text,
              unit: "",
              url: "Integral_love",
              value: memberInfo.member.integral_show.data
            })
          }
          if(memberInfo.member.love_show?.is_show){
            _data.assets.push({
              min_url: "/packageB/member/love/Love_index/Love_index",
              name: memberInfo.member.love_show.text,
              unit: "",
              url: "love_index",
              value: memberInfo.member.love_show.data
            })
          }
          
          wx.stopPullDownRefresh();

          // 底部导航数据
          let plugins_data = res.data.plugins_data;
          plugins_data.nav.forEach((key) =>
            _data.plugin_data.push({
              code: key.code == 'recommend_goods'? 'recommendGoods':'',
              name: key.name
            })
          );          

          if (plugins_data && plugins_data.nav.length > 0) {
            // 模板1 底部选项卡装修，后端默认返回第一个标签页对应的列表数据
            _data.plugin_active = _data.plugin_data[0].code;
            this.data[_data.plugin_active].list = plugins_data.data;
            _data[_data.plugin_active] = this.data[_data.plugin_active];
            
          }

          // 处理插件列表
          if (memberInfo.plugin) {
            let page = Math.ceil(memberInfo.plugin.length / 10); //==> 页数
            let num = 10; // ==> 每页多少个
            let _plugin_list = [];
            for (let i = 0; i < page; i++) {
              _plugin_list.push(memberInfo.plugin.slice(i * num, (i + 1) * num));
            }
            _data.plugins.body = _plugin_list;
            _data.plugins.head = memberInfo.plugin_head;
          }

          this.setData(_data);
          let audioFlag = _data.assets.some((item) => item.is_change == 1);
          this.assetsAudio(_data.other,audioFlag);
          // 处理订单列表
          if (memberInfo.order) {
            let order_list = [];
            for (let i = 0; i < memberInfo.order.length; i++) {
              if (memberInfo.order[i].key === "order") {
                memberInfo.order[i].order.push({
                  status: -1,
                  status_name: "全部订单",
                  total: 0,
                  class: "icon-fontclass-quanbudingdan"
                });
              }
              order_list.push({
                key: memberInfo.order[i].key,
                name: memberInfo.order[i].title,
                title: memberInfo.order[i].title,
                data: memberInfo.order[i].order
              });
            }
            this.setData({
              order: order_list
            });
          }
        } else {
          app.tips(res.msg);
        }
        this.setData({
          firstshow: true,
        });
      },
    });
  },

  // ---------团队名称插件-------
  teamCancelTap() {
    this.setData({
      teamNameShow: false
    })
  },
  childEdit(e) {
    this.setData({
      ['member_info.member_team.team_name']: e.detail
    })
  },
  TapEdit() {
    if (this.data.member_info.member_team.can_edit) {
      this.setData({
        teamNameShow: true
      })
    }
  },
  // ---------团队名称插件 end-------

  handleContact(e) {
    let _url = e.currentTarget.dataset.url;
    if (_url) {
      wx.navigateTo({
        url: _url,
        fail: function (err) {
          app.tips('客服路径错误');
        }
      });
    }
  },

  firstlogin() {
    let firstlogin = false;
    try {
      var value = wx.getStorageSync("wx_token");
      firstlogin = value ? false : true;
      this.setData({
        loginshow: value ? false : true,
      });
    } catch (e) {
      // Do something when catch error
    }
    return firstlogin;
  },
  gotologin() {
    app.seyzredirect();
    wx.navigateTo({
      url: "/pages/login/login",
    });
  },
  toLogin(){
    this.setData({
      lsgow: true
    });
  },
  getUserProfileTap(e) {
    if(!this.data.tapSelectAgreement && this.data.PlatformAgreement) {
      app.tips('请阅读并勾选隐私协议')
      return
    }
    if (this.data.canIUseGetUserProfileTap) return;
    console.log('2222222222')
    this.setData({
      canIUseGetUserProfileTap: true
    });
    if (this.data.canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '获取用户信息',
        success: (_info) => {
          let info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': "",
            'gender': _info.userInfo.gender
          };
          this.loginbtn(info);
        },
        fail: (e) => {
          console.log(e)
          this.setData({
            canIUseGetUserProfileTap: false
          });
        }
      });
    } else {
      let _info = e.detail;
      let info = {
        'nickName': _info.userInfo.nickName,
        'avatarUrl': "",
        'gender': _info.userInfo.gender
      };
      this.loginbtn(info);
    }

  },
  loginbtn(_info) {
    if (this.data.logintap) {
      return; // 正在请求 直接return
    }
    this.setData({
      logintap: true
    });
    var that = this;
    console.log("登录中...");
    wx.login({
      success: function (_json) {
        console.log("login登录成功，获取用户info");
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2',
              login_param:app.globalData.loginScene
            },
            success: function (res) {
              var _data = res.data;
              console.log("登录接口", res);
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              if (_data.result == 1) {
                // 存储key
                if (_data.data.user_info) {
                  wx.setStorageSync("nickname", _data.data.user_info.nickname);
                }
                if (_data.msg.session) {
                  wx.setStorageSync('session', _data.msg.session);
                }
                // wx.setStorage({
                // 	key: "session",
                // 	data: _data.msg.session
                // })
                wx.setStorage({
                  key: "openid",
                  data: _data.data.openid
                });
                if (_data.msg.wx_token) {
                  wx.setStorageSync('wx_token', _data.msg.wx_token);
                }
                // wx.setStorage({
                // 	key: "wx_token",
                // 	data: _data.msg.wx_token
                // })
                if (_info) {
                  wx.setStorageSync('userInfo', _info);
                }
                //that.globalData.uid = _data.msg.uid;
                wx.setStorage({
                  key: "yz_uid",
                  data: _data.msg.uid
                });
                if (_data.data.is_first_time_bind) {
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                } else {
                  that.getInvite();
                }
                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
              } else {
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                  }
                });
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: function (res) {
              that.setData({
                logintap: false,
                canIUseGetUserProfileTap: false
              });
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            }
          });
        } else {
          that.setData({
            logintap: false,
            canIUseGetUserProfileTap: false
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: function (res) {
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
    });
  },
  //是否开启邀请页面
  getInvite() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data, 'member'); //定义在 behaviors里面
          } catch (e) {
            wx.reLaunch({
              url: "/packageG/index/index",
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  turnTo() {
    if (this.data.advertising.is_minapp == 2) {
      if (this.data.advertising.minapp_sid) {
        if (this.data.advertising.minapp_link2) {
          try {
            wx.navigateToMiniProgram({
              appId: this.data.advertising.minapp_sid,
              path: this.data.advertising.minapp_link2,
              extraData: {},
              envVersion: "release",
              success(res) {
                // 打开成功
              },
              fail(res) {
                wx.showToast({
                  title: "小程序跳转失败",
                  icon: "none",
                  duration: 2000,
                });
              },
            });
          } catch (e) {
            wx.showToast({
              title: "小程序跳转失败",
              icon: "none",
              duration: 2000,
            });
          }
        } else {
          wx.showToast({
            title: "请设置跳转小程序后的跳转链接",
            icon: "none",
            duration: 2000,
          });
        }
      } else {
        wx.showToast({
          title: "请设置小程序所需跳转appId",
          icon: "none",
          duration: 2000,
        });
      }
    } else {
      let url = this.data.advertising.minapp_link;
      try {
        wx.navigateTo({
          url: url,
        });
      } catch (e) {
        wx.showToast({
          title: "链接设置错误",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
  getNavigateUrl(url = '/packageA/member/myOrder_v2/myOrder_v2', status, orderType = "") {
    return `${url}?status=${status}${orderType ? "&orderType=" + orderType : ""}`;
  },
  toOrderList(e) {
    const item = e.currentTarget.dataset.item;
    const orderKey = e.currentTarget.dataset.name;
    let status = Number(item.status) + 1;
    let orderType = orderKey;
    let pageUrl;

    if (orderKey !== 'hotel_order' && item.status === 11) {
      return this.goaftersaleslist();
    }
    switch (orderKey) {
      case 'shop':
      case 'order':
        break;
      case 'hotel':
        status = item.status === 11 ? 5 : Number(item.status) + 1;
        break;
      case 'fight-groups':
      case 'fight_groups_order':
        status = item.status != 0 ? Number(item.status) + 2 : Number(item.status) + 1;
        orderType = "groups";
        break;
      case 'snatch-regiment':
        status = Number(item.status) + 1;
        orderType = "grabGroup";
        break;
      case 'lease-toy':
        status = Number(item.status) + 1;
        orderType = "lease_toy";
        break;
      case 'live-install-work':
        status = item.status === -1 ? 1 : item.status;
        pageUrl = '/packageH/installationSever/installationSeverHome/installationSeverHome';
        break;
      case 'live-install':
        status = item.status === 3 ? 4 : Number(item.status) + 1;
        pageUrl = '/packageH/installationSever/installationSeverMemberHome/installationSeverMemberHome';
        break;
      case 'aggregation-cps':
        if (item.status === -3) {
          pageUrl = '/packageA/member/order/cpsCoupon/cpsCoupon';
        } else {
          pageUrl = '/packageA/member/order/cpsOrder/cpsOrder';
        }
        status = item.status === 3 ? null : item.status;
        break;
      case 'group-work':
        status = Number(item.status) + 1;
        orderType = "groupWork";
        break;
      case 'ywm-fight-groups':
        status = item.status;
        orderType = "ywmgroups";
        break;
      case 'coupon-store':
        pageUrl = '/packageF/consumption/orderList/orderList';
        status = item.status === -2 ? 4 : item.status;
        break;
      case "travel-around":
        status = Number(item.status) + 1;
        orderType = "travelAround";
        break;
      case "yz-supply-cake":
        orderType = "sachertorte";
        break;
      case "union-cps":
        pageUrl = '/packageJ/unionCps/order/order';
        status = item.status === -2 ? 4 : item.status;
        break;
      case "tiktokcps":
        status = item.status;
        pageUrl = '/packageF/cps/order/order';
        break;
      case "meituan-group-buy":
        status = item.status;
        pageUrl = '/mircoApp/meituan_refund/order/order';
        break;
      case "collection-center":
        orderType = "collectionCenter";
        if(Number(item.status) == 3 ) status = 2;
        break;
      case "meituan":
        status = item.status;
        pageUrl = '/mircoApp/meituan_refund/order/order'
        break;
      default:
        console.error("Invalid order key:", orderKey);
        // return;
    }

    if(Number(item.status) == -2 && status < 0) status = 0;

    wx.navigateTo({
      url: this.getNavigateUrl(pageUrl, status, orderType),
    });
  },
  goaftersaleslist: function () {
    wx.navigateTo({
      url: "/packageD/member/myOrder/Aftersaleslist/Aftersaleslist",
    });
  },
  async handlePlugin(event) {
    let plugin_active = "";
    if (event.detail) {
      plugin_active = event.detail.name;
    } else if (event.name) {
      plugin_active = event.name;
    }

    this.setData({
      plugin_active: plugin_active
    });
    this.data.decorate_isLoadMore = true;

    if (this.data.store_alone_temp == 1) {
      // 企业独立模块
      // this.getPlugins("plugin.store-alone-temp.frontend.member.nav-data", {
      //   page: 1,
      //   code: this.data.plugin_active
      // }, this.data.plugin_active);
      return;
    }

    if(plugin_active == 'storeCashier'){
      this._getLocation((mapdata, e) => {
        this.point = {
          lat: e.lat,
          lng: e.lng,
        }
        this._handleBottomPluginData(this.data.plugin_active, "getList");
      });
    } else {
      this._handleBottomPluginData(this.data.plugin_active, "getList");
    }
  },

  async _handleBottomPluginData(name, fn) {
    /*
      处理 模板1 底部装修组件数据加载
      getList() // 这里处理获取首次或者第一页的请求
      getMore() // 这里处理加载更多
      }
    */
    let _this = this;
    let _url = 'member.member.plugin-data';
    if (this.data.store_alone_temp == 1 && name == 'fightGroups') {
      // 企业独立
      _url = "plugin.store-alone-temp.frontend.member.nav-data";
    }
    if (fn == 'getList') {
      app._postNetWork({
        url: app.getNetAddresss(_url),
        data: {
          page: 1,
          code: name,
          lng: this.point?.lng || '0',
          lat: this.point?.lat|| '0'
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            _this.data[name].current_page = res.data.current_page;
            _this.data[name].last_page = res.data.last_page;

            if (name == 'microCommunities' || name == 'storeCashier'||name == 'limitBuyGoods'||name == 'room') {
              _this.data[name].list = res.data;
            } else if (name == 'videoShare') {
              _this.data[name].list = res.data.list;
              _this.data[name].current_page = res.data.list.current_page;
              _this.data[name].last_page = res.data.list.last_page;
            } else if (name == 'article') {
              _this.data[name].list = res.data.articles;
              _this.data[name].current_page = res.data.articles.current_page;
              _this.data[name].last_page = res.data.articles.last_page;
            } else {
              _this.data[name].list = res.data.data;
            }

            this.setData({
              [name]: _this.data[name]
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {}
      });
    }
    if (fn == 'getMore') {
      _this.data.decorate_isLoadMore = false;
      if (_this.data[name].current_page < _this.data[name].last_page) {
        _this.data[name].current_page += 1;

        let component_key = {
          recommendGoods: 'recommend_goods',
          limitBuyGoods: 'limit_buy_goods',
          article: 'article',
          videoShare: 'video_share',
          microCommunities: 'micro_communities',
          storeCashier: 'store_cashier',
          room: 'room',
          fightGroups: 'fight_groups',
          ywmFightGroups: 'ywm_fight_groups'
        }
        let _selectComponent = _this.selectComponent(`#${component_key[name]}`);

        if (name === 'recommendGoods'||name === 'limitBuyGoods'||name === 'videoShare') {
          _selectComponent.loadMoreMemberData();
        } else if (name === 'article'||name === 'microCommunities') {
          _selectComponent.getMoreData();
        } else if (name === 'storeCashier') {
          _selectComponent.getMoreList();
        } else if (name === 'room') {
          _this.data.decorate_isLoadMore = true;
        } else if (name === 'fightGroups'||name === 'ywmFightGroups') {
          app._postNetWork({
            url: app.getNetAddresss('member.member.plugin-data'),
            data: {
              page: _this.data[name].current_page,
              code: name
            },
            success: (resdata) => {
              var res = resdata.data;
              if (res.result == 1) {
                let _data = res.data.data;                
                let _list = _this.data[name].list.concat(_data);
                _this.setData({
                  [name + '.list']: _list
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.msg,
                  duration: 1500
                });
              }
            },
            fail: function (res) {}
          });
        }
      }
    }
  },

  setLoadMore(event) {
    this.setData({
      decorate_isLoadMore: event.detail.isLoadMore
    });
  },

  openService() {
    this.setData({
      showPopup: true
    });
  },
  closeService() {
    this.setData({
      showPopup: false
    });
  },

  // 获取授权手机号 ============= start =============
  async getPhoneNumber(e) {
    let info = e.detail;
    if (info.errMsg == 'getPhoneNumber:ok') {
      let mobile = await this.getPhone_index(info.code);
      this.data.AuthorizedPhone = mobile;
      await this.getPrepBind(mobile);
      await this.setBindPhone();
      this.getInvite();
    } else {
      this.getInvite();
    }
  },

  getPhone_index(info) {
    wx.showLoading({
      title: '加载中',
    });
    let urlStr = app.getNetAddresss('member.member.miniMemberMobile');
    return new Promise((resolve, reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        validateBol: 2,
        data: {
          code: info,
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res.data.phone_info.purePhoneNumber);
          } else {
            wx.hideLoading({
              success: (res) => {},
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  setBindPhone(e) {
    wx.hideLoading({
      success: (res) => {},
    });
    let urlStr = app.getNetAddresss('member.member.bindMobile');
    return new Promise((resolve, reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          mobile: this.data.AuthorizedPhone,
          mini_first_time_bind: 1
        },
        success: (resdata) => {
          var res = resdata.data;

          if (this.data.changidInfo && this.data.changidInfo.change_uid) {
            // 更新uid为合并后的会员id
            wx.setStorage({
              key: "yz_uid",
              data: this.data.changidInfo.change_uid,
            });
          }

          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.getInvite();
          resolve();
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  // 获取授权手机号 ============= end =============

  //先验证是否导致会员id变更
  getPrepBind(mobile) {
    let urlStr = app.getNetAddresss("member.member.prepBind");
    return new Promise((resolve, reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          mobile: mobile,
          not_validate_page: '0'
        },
        validateBol: 2,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.is_show) {
              // 显示 导致会员id变更 弹窗
              wx.hideLoading({
                success: (res) => {},
              });
              let basic_info = this.basic_info;
              this.setData({
                balance: wx.getStorageSync('balance'),
                point: wx.getStorageSync('integral'),
                showChangeID: true,
                changidInfo: {
                  uid: res.data.uid,
                  change_uid: res.data.change_uid
                }
              });
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject(res);
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },

  imageLoad: function (e) {
    let image = {
      width: e.detail.width, //获取图片真实宽度
      height: e.detail.height
    };
    this.setData({
      images: image
    });
  },
});